import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import type { RouteRecordRaw } from 'vue-router'

// 使用懒加载但添加错误处理
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue').catch(() => import('@/views/Login.vue')),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue').catch(() => import('@/layouts/MainLayout.vue')),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue').catch(() => import('@/views/Dashboard.vue')),
        meta: { title: '仪表盘' }
      },
      {
        path: '/departments',
        name: 'Departments',
        component: () => import('@/views/Departments.vue').catch(() => import('@/views/Departments.vue')),
        meta: { title: '部门管理' }
      },
      {
        path: '/employees',
        name: 'Employees',
        component: () => import('@/views/Employees.vue').catch(() => import('@/views/Employees.vue')),
        meta: { title: '员工管理' }
      },
      {
        path: '/students',
        name: 'Students',
        component: () => import('@/views/Students.vue').catch(() => import('@/views/Students.vue')),
        meta: { title: '学员管理' }
      },
      {
        path: '/courses',
        name: 'Courses',
        component: () => import('@/views/Courses.vue').catch(() => import('@/views/Courses.vue')),
        meta: { title: '课程管理' }
      },
      {
        path: '/orders',
        name: 'Orders',
        component: () => import('@/views/Orders.vue').catch(() => import('@/views/Orders.vue')),
        meta: { title: '订单管理' }
      },
      {
        path: '/performance',
        name: 'Performance',
        component: () => import('@/views/Performance.vue').catch(() => import('@/views/Performance.vue')),
        meta: { title: '业绩统计' }
      },
      {
        path: '/traffic',
        name: 'Traffic',
        component: () => import('@/views/Traffic.vue').catch(() => import('@/views/Traffic.vue')),
        meta: { title: '流量统计' }
      },
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  if (to.meta.requiresAuth && !userStore.isAuthenticated) {
    next('/login')
  } else if (to.path === '/login' && userStore.isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

export default router
